package com.example.shoppingmallclient.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.shoppingmallclient.R;
import com.example.shoppingmallclient.ServerIp;
import com.example.shoppingmallclient.activity.ShowProductDetail;
import com.example.shoppingmallclient.adapter.ProductListAdapter;
import com.example.shoppingmallclient.vo.ProductListVo;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 袁梦达 2019012364
 */

@SuppressWarnings("all")
public class FragmentSecond extends Fragment {

    private List<ProductListVo> list;
    private ListView listView;
    private View dialogView;
    private Button btnClose;
    private boolean flag = true;
    private AlertDialog alertDialog;

    private Handler myHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 100:
                    list = (List<ProductListVo>) msg.obj;
                    ProductListAdapter adapter = new ProductListAdapter(list, R.layout.product_item, getContext());
                    listView.setAdapter(adapter);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view =inflater.inflate(R.layout.product_list, container, false);

        List<ProductListVo> productList = new ArrayList<>();

        listView = view.findViewById(R.id.lv);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ShowProductDetail.class);
                intent.putExtra("productId", list.get(position).getId());
                startActivity(intent);
            }
        });

        if(flag){
            dialogView = getLayoutInflater().inflate(R.layout.discount_dialog, null, false);
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setView(dialogView);
            alertDialog = builder.create();
            alertDialog.show();
            flag = false;
        }
        btnClose = dialogView.findViewById(R.id.close);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        getProductList(productList);

        return view;
    }



    private void getProductList(List<ProductListVo> productList){
        new Thread(){
            @Override
            public void run() {
                //使用网络访问服务器端
                try {
                    String serverUrl = "http://" + ServerIp.ServerIp + ":8080/DressDiscountListServlet";
                    URL url = new URL(serverUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");

                    InputStream is = connection.getInputStream();
                    StringBuffer stringBuffer = new StringBuffer();
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = is.read(bytes)) != -1){
                        stringBuffer.append(new String(bytes, 0, len));
                    }

                    String substring = null;
                    if(stringBuffer.toString().length() > 1){
                        substring = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                    }
                    String[] msgs = substring.split("#");
                    for (String msg : msgs) {
                        String[] strings = msg.split("@");

                        Integer id = Integer.valueOf(strings[0]);

                        String baseInformation = strings[1];

                        String image = strings[2];
                        URL imgUrl = new URL(image);
                        InputStream inputStream = imgUrl.openStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                        double price = Double.parseDouble(strings[3]);

                        ProductListVo product = new ProductListVo(id, baseInformation, price, bitmap);
                        productList.add(product);
                    }

                    Message msg = new Message();
                    msg.what = 100;
                    msg.obj = productList;
                    myHandler.sendMessage(msg);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
